﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.IO;
using System.Collections.Generic;
using CommonLibraries.DeviceLibrary;
using CommonLibraries.DeviceLibrary.Helpers;
using demo.AppCode.Entities;
using System.Threading;
namespace demo
{
    public partial class PhotoForm : BaseForm
    {
        #region Properties
        protected int m_PositionInsert;
        public int SetPositionId
        {
            set { m_PositionInsert = value; }
        }
        protected PictureBox m_TempPictureBox;
        public EImagePath[] m_PathPreviewImages = new EImagePath[4];
        protected int m_ImageCounter = 0;
        protected ViewPhotoForm m_ViewPhotoForm = null;
        #endregion


        public PhotoForm()
        {
            
            InitializeComponent();
            

        }
        protected void PhotoForm_Load(object sender, System.EventArgs e)
        {
            try
            {
                LoadCombos();
                this.buttonFocus.Focus();
                CheckImagesFolder();


                if (m_Camera.PowerState == CommonLibraries.DeviceLibrary.PowerStates.Off)
                    m_Camera.On(pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y);
                else
                    m_Camera.SetCameraFinder((int)PowerStates.On, pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y);

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("PhotoForm_Load->" + ex.InnerException + "\n"+ex.StackTrace);
            } 
        }
        #region Take Photo
        private void Shutter()
        {
            try
            {
                string _FileName = "";
                string _FileNamePreview = "";
                if (m_ImageCounter >= 4)
                {
                    m_Camera.SetCameraFinder(0, 0, 0);
                    MessageBox.Show(Constants.K_Alert4Photos);
                    m_Camera.SetCameraFinder((int)PowerStates.On, pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y); //Power On Camera
                    return;
                }
                else
                {
                    _FileName = Constants.K_ImagesFolder + m_PositionInsert.ToString() + "_" + m_ImageCounter + ".jpeg";
                    _FileNamePreview = Constants.K_ImagesFolder + m_PositionInsert.ToString() + "_" + m_ImageCounter + "_4x.jpeg";
                    if (TakePhoto(_FileName, _FileNamePreview))
                    {
                        AddImagePath(_FileName, _FileNamePreview);
                        LoadAllImages();
                    }

                }
                this.buttonFocus.Focus();               
            }
            catch (Exception ex)
            {

                ErrorManager.CreateDebug("Shutter->" + ex.Message + "\n"+ex.StackTrace);
            }
        }
        private bool TakePhoto(string FileName, string FileNamePreview)
        {
            int i = 0;
            bool _Taken = false;
            while (i < 3 && !_Taken)
            {
                if (m_Camera.ImageSize == 0)
                {
                    m_Camera.SetCameraFinder((int)PowerStates.Off, 0, 0);
                    m_Camera.TakePhoto(FileNamePreview, 3);
                    m_Camera.TakePhoto(FileName, m_Camera.ImageSize);
                    
                    if (File.Exists(FileName) && File.Exists(FileNamePreview))
                    {
                        _Taken = true;
                        m_Camera.SetCameraFinder((int)PowerStates.On, pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y); //Power On Camera
                    }
                    else
                    {
                        GC.Collect();
                        if (i == 2)
                        {
                            m_Camera.Off(0, 0);
                            MessageBox.Show(Constants.K_AlertImposibleTakePhoto, "");
                            m_Camera.On(pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y);
                            return false;
                        }
                    }
                    i++;
                }
                else
                {
                    m_Camera.TakePhoto(FileNamePreview, 3);
                    if(File.Exists(FileNamePreview))
                    {
                        File.Copy(FileNamePreview,FileName);
                    }
                }
            }
            return true;
        }
        private bool LoadAllImages()
        {
            try
            {
                Bitmap _TempPhoto = null;
                for (Int32 i = 0; i < m_PathPreviewImages.Length; i++)
                {
                    if (m_PathPreviewImages[i] != null)
                    {
                        if (m_PathPreviewImages[i].Show == false)
                        {
                            if (File.Exists(m_PathPreviewImages[i].ImagePath))
                                _TempPhoto = new Bitmap(m_PathPreviewImages[i].ImagePathPreview);
                            m_PathPreviewImages[i].Show = true;
                            switch (i)
                            {
                                case 0:
                                    pictureBoxTakedPhoto0.Image = (Image)_TempPhoto;
                                    pictureBoxTakedPhoto0.Click += new EventHandler(PictureBoxPreview_Click);
                                    break;
                                case 1:
                                    pictureBoxTakedPhoto1.Image = (Image)_TempPhoto;
                                    pictureBoxTakedPhoto1.Click += new EventHandler(PictureBoxPreview_Click);
                                    break;
                                case 2:
                                    pictureBoxTakedPhoto2.Image = (Image)_TempPhoto;
                                    pictureBoxTakedPhoto2.Click += new EventHandler(PictureBoxPreview_Click);
                                    break;
                                case 3:
                                    pictureBoxTakedPhoto3.Image = (Image)_TempPhoto;
                                    pictureBoxTakedPhoto3.Click += new EventHandler(PictureBoxPreview_Click);
                                    break;
                            }
                        }
                    }
                }
                return true;
                //int _X = 12;
                //int _Y = 5;
                //int _Distance = 0;
                //Bitmap _Bmp = null;
                //PictureBox PictureBoxPreview;
                //for (Int32 i = 0; i < m_PathPreviewImages.Length; i++)
                //{
                //    //define X Distance between photos
                //    _Distance = 45 * i;
                //    if (m_PathPreviewImages[i] != null)
                //    {
                //        PictureBoxPreview = new PictureBox();
                //        PictureBoxPreview.Name = i.ToString();
                //        PictureBoxPreview.Tag = i.ToString();
                //        PictureBoxPreview.Width = 41;
                //        PictureBoxPreview.Height = 42;
                //        PictureBoxPreview.SizeMode = PictureBoxSizeMode.StretchImage;
                //        PictureBoxPreview.Location = new System.Drawing.Point(_X, _Y + _Distance);
                //        if (m_PathPreviewImages[i].Show == false)
                //        {
                //            _Bmp = null;
                //            if (File.Exists(m_PathPreviewImages[i].ImagePath))
                //                _Bmp = new Bitmap(m_PathPreviewImages[i].ImagePath);
                //            m_PathPreviewImages[i].Show = true;
                //            //Attach photo to the picturebox
                //            PictureBoxPreview.Image = (Image)_Bmp;
                //            PictureBoxPreview.Click += new EventHandler(PictureBoxPreview_Click);
                //            PictureBoxPreview.ContextMenu = contextMenuPreviewPhoto;
                //            PanelPhotos.Controls.Add(PictureBoxPreview);
                //        }
                //    }
                    
                //}
                
            }
            catch (OutOfMemoryException ex)
            {
                ErrorManager.CreateDebug("Waiting for finalizers to run...");
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.Collect();
                GC.Collect();
                LoadAllImages();
                return false;
            }
            catch (Exception e)
            {
                ErrorManager.CreateDebug("LoadAllImages->" + e.Message);
                return false;
            }
        }

        private void PictureBoxPreview_Click(object sender, EventArgs e)
        {
            m_TempPictureBox = (PictureBox)sender;
            if (m_TempPictureBox.Image != null)
            {
                Point _NewPoint = new Point(panelImageContextMenu.Location.X, panelImageContextMenu.Location.Y);
                contextMenuPreviewPhoto.Show(panelImageContextMenu, _NewPoint);
            }
        }
        #endregion

        #region Combos
        protected void LoadCombos()
        {
            LoadModeCombo();
            LoadZoomCombo();
        }

        protected void LoadModeCombo()
        {
            ComboBoxConfigMode.Items.Insert(0, "Day");
            ComboBoxConfigMode.Items.Insert(1, "Night");
            ComboBoxConfigMode.Items.Insert(2, "Auto");
            ComboBoxConfigMode.SelectedIndex = 2;
            ComboBoxConfigMode.SelectedValueChanged += new EventHandler(ComboBoxConfigMode_SelectedValueChanged);
        }

        void ComboBoxConfigMode_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox _tempCombo = (ComboBox)sender;
            int SelectedIndex = _tempCombo.SelectedIndex;
            switch (SelectedIndex)
            {
                case 0:
                    m_Camera.PictureMode = CameraModes.IntoSun;
                    break;
                case 1:
                    m_Camera.PictureMode = CameraModes.Night;
                    break;
                default:
                    m_Camera.PictureMode = CameraModes.Normal;
                    break;
            }
        }

        protected void LoadZoomCombo()
        {
            try
            {
                comboBoxZoom.Items.Insert(0, "0x");
                comboBoxZoom.Items.Insert(1, "1x");
                comboBoxZoom.Items.Insert(2, "2x");
                comboBoxZoom.Items.Insert(3, "4x");
                comboBoxZoom.SelectedIndex = 0;
                comboBoxZoom.SelectedValueChanged += new EventHandler(comboBoxZoom_SelectedValueChanged);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void comboBoxZoom_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox _tempCombo = (ComboBox)sender;
            int SelectedIndex = _tempCombo.SelectedIndex;
            switch (SelectedIndex)
            {
                case 0:
                    m_Camera.Zoom = ZoomLevels.x0;
                    break;
                case 1:
                    m_Camera.Zoom = ZoomLevels.x1;
                    break;
                case 2:
                    m_Camera.Zoom = ZoomLevels.x2;
                    break;
                case 3:
                    m_Camera.Zoom = ZoomLevels.x4;
                    break;
            }
        }

        #endregion

        private void transparentLabelShutter_Click(object sender, EventArgs e)
        {
            Shutter();
        }

        private void transparentLabelExit_Click(object sender, EventArgs e)
        {
            ClosePhotoForm();
        }

        private void ClosePhotoForm()
        {
            try
            {
                m_Camera.SetCameraFinder((int)PowerStates.Off, 0, 0);
                UpdateCountImages();              
                m_ImageCounter = 0;
                CleanPathPreviewImages();
                this.Close();

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("transparentLabelExit_Click->" + ex.Message);
            }
        }

        private void CleanPathPreviewImages()
        {
            for (int i = 0; i < m_PathPreviewImages.Length; i++)
                m_PathPreviewImages[i] = null;
        }

        void menuItemDeletePhoto_Click(object sender, System.EventArgs e)
        {
            try
            {
                Int32 _Index = Int32.Parse(m_TempPictureBox.Tag.ToString());
                m_PathPreviewImages[_Index].Deleted = true;
                m_PathPreviewImages[_Index].Show = true;
                File.Delete(m_PathPreviewImages[_Index].ImagePath);
                File.Delete(m_PathPreviewImages[_Index].ImagePathPreview);
                m_TempPictureBox.Click -= new EventHandler(PictureBoxPreview_Click);
                m_TempPictureBox.Image = null;
                m_ImageCounter--;
            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("menuItemDeletePhoto_Click->" + ex.InnerException + "\n"+ex.StackTrace);
            }
        }
        void menuItemViewPhoto_Click(object sender, System.EventArgs e)
        {
            try
            {
                m_Camera.SetCameraFinder((int)PowerStates.Off, 0, 0);
                m_ViewPhotoForm = new ViewPhotoForm();
                m_ViewPhotoForm.ImageToView = m_TempPictureBox.Image;
                m_ViewPhotoForm.ShowDialog();
                m_ViewPhotoForm.Dispose();
                m_Camera.SetCameraFinder((int)PowerStates.On, pictureBoxPreviewPhoto.Location.X, pictureBoxPreviewPhoto.Location.Y);

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("menuItemViewPhoto_Click->" + ex.InnerException + "\n"+ex.StackTrace);
            }
        }

        protected void DeletePictures(string FolderPath)
        {
            try
            {
                DirectoryInfo _Directory = new DirectoryInfo(FolderPath);
                FileInfo[] _Files = _Directory.GetFiles();
                foreach (FileInfo _File in _Files)
                    _File.Delete();
            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("DeletePictures->" + ex.InnerException + "\n" + ex.StackTrace);
            }
        }

        public void InsertImages()
        {
            DateTime Start = System.DateTime.Now;
            CleandImagesPictureBox();
            SqlCeConnection _Cn = null;
            SqlCeCommand command = null;
            try
            {
                _Cn = new SqlCeConnection();
                _Cn.ConnectionString = ("Data Source =" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\demo.sdf;"));
                _Cn.Open();
                
                if (m_PathPreviewImages.Length > 0)
                {
                    string _FinalName = "";
                    byte[] _Buffer;
                    foreach (EImagePath _PhotoPath in m_PathPreviewImages)
                    {
                        if (File.Exists(_PhotoPath.ImagePath))
                        {
                            string sql = "INSERT INTO [tb_Images] ([PositionFK], [Name], [Bytes]) VALUES (@IdPosition , @Name , @imageBytes)";
                            _FinalName = m_PositionInsert + "_Sample_" + System.DateTime.Now.Ticks.ToString() + ".jpeg";

                            _Buffer = ImageHelper.GetImageBytes(_PhotoPath.ImagePath);

                            //open sqlce connection to insert new image

                            command = new SqlCeCommand(sql, _Cn);

                            command.Parameters.Add("@Name", SqlDbType.NVarChar, 255);
                            command.Parameters["@Name"].Value = _FinalName;


                            command.Parameters.Add("@IdPosition", SqlDbType.Int);
                            command.Parameters["@IdPosition"].Value = m_PositionInsert;


                            command.Parameters.Add("@imageBytes", SqlDbType.Image, _Buffer.Length);
                            command.Parameters["@imageBytes"].Value = _Buffer;
                            command.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorManager.CreateDebug("InsertImage->" + e.Message);
            }
            finally
            {
                DateTime End = System.DateTime.Now;
                TimeSpan Time = Start.Subtract(End);
                string stemp = "Tiempo que tarda en Grabar min:" + Time.Minutes + " sec: " + Time.Seconds + "";
                ErrorManager.CreateDebug(stemp);
                _Cn.Close();
                _Cn.Dispose();
            }

        }

        public override void buttonFocus_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            switch (e.KeyValue)
            {
                case 13:
                    Shutter();
                    break;
                case 27:
                    ClosePhotoForm();
                    break;
            }
        }

        protected void AddImagePath(string ImagePath, string ImagePathPreview)
        {
            bool FoundPosition = false;
            int i = 0;
            try
            {
                while (i < m_PathPreviewImages.Length && FoundPosition == false)
                {
                    if (m_PathPreviewImages[i] == null || m_PathPreviewImages[i].Deleted == true)
                    {
                        m_PathPreviewImages[i] = new EImagePath(ImagePath, ImagePathPreview);
                        FoundPosition = true;
                        m_ImageCounter++;
                    }
                    i++;
                }

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("menuItemDeletePhoto_Click->" + ex.InnerException + "\n"+ex.StackTrace);
            }
        }

        protected void UpdateCountImages()
        {
            demoDataSetTableAdapters.tb_PositionsTableAdapter tb_PositionsTableAdapter = new demo.demoDataSetTableAdapters.tb_PositionsTableAdapter();
            tb_PositionsTableAdapter.UpdateCountImages(m_ImageCounter, m_PositionInsert);
            tb_PositionsTableAdapter.Dispose();
        
        }

        protected void CleandImagesPictureBox()
        {
            PanelPhotos.Controls.Clear();

        
        }
        private void CheckImagesFolder()
        {
            if (!Directory.Exists(Constants.K_ImagesFolder))
                Directory.CreateDirectory(Constants.K_ImagesFolder);
        }


        void PhotoForm_Disposed(object sender, System.EventArgs e)
        {
            m_GPS.HasSolutionChanged -= new EventHandler(m_GPS_HasSolutionChanged);
        }

    }
}